package com.engine.cyjt.workflow.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.cyjt.workflow.utils.WfUtil;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.jobs.common.DocUtil;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: ecology-9
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2023-05-10
 * @Description: 调用自定义流程接口
 * @ModifyLog:
 **/

public class WeaCyjtWorkflowWeb extends BaseBean {
    /**
     * @Description: 流程创建
     * @Param: [request, response]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2023/7/17
     */

    @POST
    @Path("/doCreateRequest")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String doCreateRequest(JSONObject paramsJson) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        WfUtil wfUtil = new WfUtil();
        try {
            writeLog(">>>>>doCreateRequest>>>paramsJson=" + paramsJson);
            String formId = Util.null2String(paramsJson.getString("workflowId"));
            String requestName = Util.null2String(paramsJson.getString("requestName"));
            String mainData = Util.null2String(paramsJson.getString("mainData"));
            String detailData = Util.null2String(paramsJson.getString("detailData"));
            String isnextFlow = Util.null2String(paramsJson.getString("isnextFlow"));
            String loginId = Util.null2String(paramsJson.getString("loginId"));
            Map<String, Object> returnParamsMap = wfUtil.checkReqParams(paramsJson);
            String paramsCode = Util.null2String(returnParamsMap.get("code"));
            int seccategory = wfUtil.getDoccategory(formId);
            writeLog(">>>>>doCreateRequest>>>paramsCode=" + paramsCode);
            if (!"SUCCESS".equals(paramsCode)) {
                apidatas = returnParamsMap;
            } else {
                String userId = wfUtil.getResourceid(loginId);
                User user = new User(Util.getIntValue(userId));
                JSONArray mainDatalist = JSONArray.parseArray(mainData);
                Map<String, Object> mainMap = new HashMap<String, Object>();
                for (int i = 0; i < mainDatalist.size(); i++) {
                    JSONObject mainFields = mainDatalist.getJSONObject(i);
                    String fieldName = Util.null2String(mainFields.getString("fieldName"));
                    String fieldValue = Util.null2String(mainFields.getString("fieldValue"));
                    if (wfUtil.isJSONArray(fieldValue)) {
                        String docids = "";
                        JSONArray fileList = JSONArray.parseArray(fieldValue);
                        for (int l = 0; l < fileList.size(); l++) {
                            JSONObject fileJson = fileList.getJSONObject(l);
                            String filePath = Util.null2String(fileJson.getString("filePath"));
                            String fileName = Util.null2String(fileJson.getString("fileName"));
                            Map<String, Object> retMap = DocUtil.downloadByUrl(filePath);
                            if (Util.null2String(retMap.get("code")).equals("0")) {
                                String filepath = Util.null2String(retMap.get("data"));
                                writeLog(">>>>>doCreateRequest>>>filepath=" + filepath);
                                int imagefileid = DocUtil.saveImageFile(fileName, filepath);
                                writeLog(">>>>>doCreateRequest>>>imagefileid=" + imagefileid);
                                int docid = DocUtil.createDocByImagefileId(imagefileid, user, "1", "0", fileName, "", seccategory);
                                writeLog(">>>>>doCreateRequest>>>docid=" + docid);
                                docids += "".equals(docids) ? docid : "," + docid;
                            }
                        }
                        fieldValue = docids;
                    }
                    mainMap.put(fieldName, fieldValue);
                }
                String workflowId = wfUtil.getWorkflowid(formId);
                String newRequestid = wfUtil.WorkflowCreateByRequestMap(userId, workflowId, requestName, isnextFlow, mainMap);
                writeLog(">>>>>doCreateRequest>>>newRequestid=" + newRequestid);
                if (Util.getIntValue(newRequestid) > 0) {
                    if (!"".equals(detailData)) {
                        JSONArray detailDatalist = JSONArray.parseArray(detailData);
                        String mainid = Util.null2String(wfUtil.getIdByRequestId(formId, newRequestid));
                        int dtlTableSumCount = detailDatalist.size();
                        int dtlTableSuccCount = 0;
                        for (int i = 0; i < detailDatalist.size(); i++) {
                            JSONObject detailDatas = detailDatalist.getJSONObject(i);
                            String dtltableName = Util.null2String(detailDatas.getString("tableDBName"));
                            if (!"".equals(dtltableName)) {
                                writeLog(">>>>>doUpdateRequest>>>detailData>>>>dtltableName=" + dtltableName);
                                String tableRecords = Util.null2String(detailDatas.getString("workflowRequestTableRecords"));
                                boolean istableArr = wfUtil.isJSONArray(tableRecords);
                                if (!"".equals(tableRecords) && istableArr) {
                                    JSONArray recordslist = JSONArray.parseArray(tableRecords);
                                    int sumCount = recordslist.size();
                                    int succCount = 0;
                                    for (int j = 0; j < recordslist.size(); j++) {
                                        Map<String, Object> detailMap = new HashMap<String, Object>();
                                        JSONObject records = recordslist.getJSONObject(j);
                                        String tableFields = Util.null2String(records.getString("workflowRequestTableFields"));
                                        if (!"".equals(tableFields) && wfUtil.isJSONArray(tableFields)) {
                                            JSONArray tableFieldslist = JSONArray.parseArray(tableFields);
                                            for (int k = 0; k < tableFieldslist.size(); k++) {
                                                JSONObject detailFields = tableFieldslist.getJSONObject(k);
                                                String fieldName = Util.null2String(detailFields.getString("fieldName"));
                                                String fieldValue = Util.null2String(detailFields.getString("fieldValue"));
                                                if (wfUtil.isJSONArray(fieldValue)) {
                                                    String docids = "";
                                                    JSONArray fileList = JSONArray.parseArray(fieldValue);
                                                    for (int l = 0; l < fileList.size(); l++) {
                                                        JSONObject fileJson = fileList.getJSONObject(l);
                                                        String filePath = Util.null2String(fileJson.getString("filePath"));
                                                        String fileName = Util.null2String(fileJson.getString("fileName"));
                                                        Map<String, Object> retMap = DocUtil.downloadByUrl(filePath);
                                                        if (Util.null2String(retMap.get("code")).equals("0")) {
                                                            String filepath = Util.null2String(retMap.get("data"));
                                                            int imagefileid = DocUtil.saveImageFile(fileName, filepath);
                                                            int docid = DocUtil.createDocByImagefileId(imagefileid, user, "1", "0", fileName, "", seccategory);
                                                            docids += (docids.equals("") ? docid : ("," + docid));
                                                        }
                                                    }
                                                    fieldValue = docids;
                                                }
                                                detailMap.put(fieldName, fieldValue);
                                            }
                                            detailMap.put("mainid", mainid);
                                            boolean isDtlUpdate = wfUtil.updateDetailData(dtltableName, detailMap);
                                            writeLog(">>>>>doUpdateRequest>>>isDtlUpdate=" + isDtlUpdate);
                                            if (isDtlUpdate) {
                                                succCount++;
                                            }
                                        }
                                    }
                                    if (succCount == sumCount) {
                                        dtlTableSuccCount++;
                                    }
                                    writeLog(">>>>>doUpdateRequest>>>succCount=" + succCount + ",sumCount=" + sumCount);
                                }
                            }
                        }
                        writeLog(">>>>>doUpdateRequest>>>dtlTableSuccCount=" + dtlTableSuccCount + ",dtlTableSumCount=" + dtlTableSumCount);
                        if (dtlTableSumCount == dtlTableSuccCount) {
                            apidatas.put("code", "SUCCESS");
                            JSONObject datajson = new JSONObject();
                            datajson.put("requestid", newRequestid);
                            apidatas.put("data", datajson);
                            apidatas.put("message", "流程创建成功");
                        } else {
                            wfUtil.deleteWorkflow(Util.getIntValue(newRequestid), Util.getIntValue(userId));
                            apidatas.put("code", "PARAM_ERROR");
                            apidatas.put("data", "");
                            apidatas.put("message", "detailData参数错误，明细表更新失败");
                        }
                    } else {
                        apidatas.put("code", "SUCCESS");
                        JSONObject datajson = new JSONObject();
                        datajson.put("requestid", newRequestid);
                        apidatas.put("data", datajson);
                        apidatas.put("message", "流程创建成功");
                    }
                } else {
                    apidatas.put("code", "FAIL");
                    JSONObject dataJson = new JSONObject();
                    dataJson.put("requestid", newRequestid);
                    apidatas.put("data", dataJson);
                    apidatas.put("message", "流程创建失败");
                }
                writeLog(">>>>>doCreateRequest>>>apidatas=" + apidatas.toString());
            }

        } catch (Exception e) {
            System.out.println("程序内部异常:" + e);
            apidatas.put("code", "SYSTEM_INNER_ERROR");
            apidatas.put("data", "");
            apidatas.put("message", "程序内部异常");
        }
        writeLog(">>>>>doCreateRequest>>>apidatas=" + apidatas.toString());
        return JSONObject.toJSONString(apidatas);
    }

    /**
     * @Description: 流程更新
     * @Param: [request, response]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2023/9/12
     */
    @POST
    @Path("/doUpdateRequest")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String doUpdateRequest(JSONObject paramsJson) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        String formId = Util.null2String(paramsJson.getString("workflowId"));
        String requestId = Util.null2String(paramsJson.getString("requestId"));
        String mainData = Util.null2String(paramsJson.getString("mainData"));
        String detailData = Util.null2String(paramsJson.getString("detailData"));
        String loginId = Util.null2String(paramsJson.getString("loginId"));
        writeLog(">>>>>doUpdateRequest>>>paramsJson=" + paramsJson);
        String code = "";
        String data = "";
        String message = "";
        try {
            WfUtil wfUtil = new WfUtil();
            int seccategory = wfUtil.getDoccategory(formId);
            String userId = wfUtil.getResourceid(loginId);
            User user = new User(Util.getIntValue(userId));
            String checkParamsResult = wfUtil.checkUpdateParams(paramsJson);
            if ("SUCCESS".equals(checkParamsResult)) {
                JSONArray mainDatalist = JSONArray.parseArray(mainData);
                Map<String, Object> mainMap = new HashMap<String, Object>();
                for (int i = 0; i < mainDatalist.size(); i++) {
                    JSONObject mainFields = mainDatalist.getJSONObject(i);
                    String fieldName = Util.null2String(mainFields.getString("fieldName"));
                    String fieldValue = Util.null2String(mainFields.getString("fieldValue"));
                    if (wfUtil.isJSONArray(fieldValue)) {
                        String docids = "";
                        JSONArray fileList = JSONArray.parseArray(fieldValue);
                        for (int l = 0; l < fileList.size(); l++) {
                            JSONObject fileJson = fileList.getJSONObject(l);
                            String filePath = Util.null2String(fileJson.getString("filePath"));
                            String fileName = Util.null2String(fileJson.getString("fileName"));
                            Map<String, Object> retMap = DocUtil.downloadByUrl(filePath);
                            if (Util.null2String(retMap.get("code")).equals("0")) {
                                String filepath = Util.null2String(retMap.get("data"));
                                writeLog(">>>>>doCreateRequest>>>filepath=" + filepath);
                                int imagefileid = DocUtil.saveImageFile(fileName, filepath);
                                writeLog(">>>>>doCreateRequest>>>imagefileid=" + imagefileid);
                                int docid = DocUtil.createDocByImagefileId(imagefileid, user, "1", "0", fileName, "", seccategory);
                                writeLog(">>>>>doCreateRequest>>>docid=" + docid);
                                docids += "".equals(docids) ? docid : "," + docid;
                            }
                        }
                        fieldValue = docids;
                    }
                    mainMap.put(fieldName, fieldValue);
                }
                String tableName = "formtable_main_" + formId;
                writeLog(">>>>>doUpdateRequest>>>tableName=" + tableName);
                boolean isUpdate = wfUtil.updateMainData(tableName, requestId, mainMap);
                writeLog(">>>>>doUpdateRequest>>>isUpdate=" + isUpdate);
                String userid = wfUtil.getResourceid(loginId);
                if (isUpdate) {
                    if (!"".equals(detailData)) {
                        JSONArray detailDatalist = JSONArray.parseArray(detailData);
                        String mainid = Util.null2String(wfUtil.getIdByRequestId(tableName, requestId));
                        int dtlTableSumCount = detailDatalist.size();
                        int dtlTableSuccCount = 0;
                        for (int i = 0; i < detailDatalist.size(); i++) {
                            JSONObject detailDatas = detailDatalist.getJSONObject(i);
                            String dtltableName = Util.null2String(detailDatas.getString("tableDBName"));
                            if (!"".equals(dtltableName)) {
                                writeLog(">>>>>doUpdateRequest>>>detailData>>>>dtltableName=" + dtltableName);
                                String tableRecords = Util.null2String(detailDatas.getString("workflowRequestTableRecords"));
                                if (!"".equals(tableRecords)) {
                                    boolean isDelete = wfUtil.deleteDetailData(dtltableName, mainid);
                                    JSONArray recordslist = JSONArray.parseArray(tableRecords);
                                    int sumCount = recordslist.size();
                                    int succCount = 0;
                                    for (int j = 0; j < recordslist.size(); j++) {
                                        Map<String, Object> detailMap = new HashMap<String, Object>();
                                        JSONObject records = recordslist.getJSONObject(j);
                                        String tableFields = Util.null2String(records.getString("workflowRequestTableFields"));
                                        if (!"".equals(tableFields)) {
                                            JSONArray tableFieldslist = JSONArray.parseArray(tableFields);
                                            for (int k = 0; k < tableFieldslist.size(); k++) {
                                                JSONObject detailFields = tableFieldslist.getJSONObject(k);
                                                String fieldName = Util.null2String(detailFields.getString("fieldName"));
                                                String fieldValue = Util.null2String(detailFields.getString("fieldValue"));
                                                if (wfUtil.isJSONArray(fieldValue)) {
                                                    String docids = "";
                                                    JSONArray fileList = JSONArray.parseArray(fieldValue);
                                                    for (int l = 0; l < fileList.size(); l++) {
                                                        JSONObject fileJson = fileList.getJSONObject(l);
                                                        String filePath = Util.null2String(fileJson.getString("filePath"));
                                                        String fileName = Util.null2String(fileJson.getString("fileName"));
                                                        Map<String, Object> retMap = DocUtil.downloadByUrl(filePath);
                                                        if (Util.null2String(retMap.get("code")).equals("0")) {
                                                            String filepath = Util.null2String(retMap.get("data"));
                                                            int imagefileid = DocUtil.saveImageFile(fileName, filepath);
                                                            int docid = DocUtil.createDocByImagefileId(imagefileid, user, "1", "0", fileName, "", seccategory);
                                                            docids += (docids.equals("") ? docid : ("," + docid));
                                                        }
                                                    }
                                                    fieldValue = docids;
                                                }
                                                detailMap.put(fieldName, fieldValue);
                                            }
                                            detailMap.put("mainid", mainid);
                                            if (isDelete) {
                                                boolean isDtlUpdate = wfUtil.updateDetailData(dtltableName, detailMap);
                                                writeLog(">>>>>doUpdateRequest>>>isDtlUpdate=" + isDtlUpdate);
                                                if (isDtlUpdate) {
                                                    succCount++;
                                                }
                                            }
                                        }
                                    }
                                    if (succCount == sumCount) {
                                        dtlTableSuccCount++;
                                    }
                                    writeLog(">>>>>doUpdateRequest>>>succCount=" + succCount + ",sumCount=" + sumCount);
                                }
                            }
                        }
                        writeLog(">>>>>doUpdateRequest>>>dtlTableSuccCount=" + dtlTableSuccCount + ",dtlTableSumCount=" + dtlTableSumCount);
                        if (dtlTableSumCount == dtlTableSuccCount) {
                            String submitMsg = wfUtil.submitWorkflow(Util.getIntValue(requestId), Util.getIntValue(userid));
                            writeLog(">>>>>doUpdateRequest>>>submitMsg=" + submitMsg);
                            if ("success".equals(submitMsg)) {
                                code = "SUCCESS";
                                JSONObject dataJson = new JSONObject();
                                dataJson.put("requestId", requestId);
                                data = dataJson.toJSONString();
                                message = "流程更新并提交成功";
                            } else {
                                code = "NO_PERMISSION_ERROR";
                                message = "流程无权限提交或者流程已归档";
                            }

                        } else {
                            code = "PARAM_ERROR";
                            message = "detailData参数错误，明细表更新失败";
                            JSONObject dataJson = new JSONObject();
                            dataJson.put("detailData", "请检查fieldName字段，fieldValue字段类型以及tableDBName表名是否存在");
                            data = dataJson.toJSONString();
                        }
                    } else {
                        String submitMsg = wfUtil.submitWorkflow(Util.getIntValue(requestId), Util.getIntValue(userid));
                        writeLog(">>>>>doUpdateRequest>>>submitMsg=" + submitMsg);
                        if ("success".equals(submitMsg)) {
                            code = "SUCCESS";
                            JSONObject dataJson = new JSONObject();
                            dataJson.put("requestId", requestId);
                            data = dataJson.toJSONString();
                            message = "流程更新并提交成功";
                        } else {
                            code = "NO_PERMISSION_ERROR";
                            message = "流程无权限提交或者流程已归档";
                        }
                    }
                } else {
                    code = "PARAM_ERROR";
                    message = "mainData字段错误，主表更新失败";
                }
            } else {
                code = "PARAM_ERROR";
                message = checkParamsResult;
            }
            writeLog(">>>>>doUpdateRequest>>>apidatas=" + apidatas.toString());
        } catch (Exception e) {
            e.printStackTrace();
            code = "SYSTEM_INNER_ERROR";
            message = "程序内部异常";
        }
        apidatas.put("code", code);
        apidatas.put("data", data);
        apidatas.put("message", message);
        return JSONObject.toJSONString(apidatas);
    }

    /**
     * @Description: 流程删除
     * @Param: [request, response]
     * @return: java.lang.String
     * @Author: Dusongsong
     * @Date: 2023/9/12
     */
    @POST
    @Path("/doDeleteRequest")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String doDeleteRequest(JSONObject paramsJson) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        String requestId = Util.null2String(paramsJson.getString("requestId"));
        String loginId = Util.null2String(paramsJson.getString("loginId"));
        writeLog(">>>>>doDeleteRequest>>>paramsJson=" + paramsJson);
        String code = "";
        String data = "";
        String message = "";
        try {
            WfUtil wfUtil = new WfUtil();
            String userid = wfUtil.getUidByLoginid(loginId);
            boolean flag = wfUtil.deleteWorkflow(Util.getIntValue(requestId), Util.getIntValue(userid));
            if (flag) {
                code = "SUCCESS";
                JSONObject dataJson = new JSONObject();
                dataJson.put("requestId", requestId);
                data = dataJson.toJSONString();
                message = "流程删除成功";
            } else {
                code = "NO_PERMISSION_ERROR";
                message = "流程无权限删除或者流程已删除";
            }
            writeLog(">>>>>doDeleteRequest>>>apidatas=" + apidatas.toString());
        } catch (Exception e) {
            e.printStackTrace();
            code = "SYSTEM_INNER_ERROR";
            message = "程序内部异常";
        }
        apidatas.put("code", code);
        apidatas.put("data", data);
        apidatas.put("message", message);
        return JSONObject.toJSONString(apidatas);
    }

}
